<template>
    <div class="container-page">
        <div class="container-card" ref="containerRef">
            <div ref="pointsBoxRef" class="mb10">
                <searchBar :searchData="searchData" @search="onSearch" @refresh="onRefresh" />
            </div>
            <ElTable class="El-table" ref="tableRef" :loading="isLoading" row-key="id" :tableData="tableData"
                :columns="columns" :selection="selection" :single="single" :height="dynamicHeight"
                @loadScroll="loadScroll" @selection-change="onSelectionChange" @current-change="onCurrentChange"
                @sort-change="onSortChange" @filter-change="onFilterChange">
                <template #name="{ row }">
                    <div class="flex_row">
                        <img class="avatar" :src="row.avatar" alt="" srcset="">
                        <div class="font_bule ml10 ellipsis bold under-line" @click="onView(row)">
                            {{ row.name || "散客" }}
                        </div>
                    </div>
                </template>
                <template #amount_order="{ row }">
                    <div class="flex_row">
                        <div class="font_green ellipsis "> ￥{{ row.amount_order || "0" }}</div>
                    </div>
                </template>
                <template #company="{ row }">
                    <div class="ellipsis">{{ row.company || '--' }}</div>
                </template>
                <template #tag="{ row }">
                    <div class="tag-container">
                        <el-tag v-for="(tag, index) in (Array.isArray(row.tag) ? row.tag : [])" :key="index"
                            :type="getTagType(index)" size="small" class="tag-item">
                            {{ tag }}
                        </el-tag>
                    </div>
                </template>

                <!-- 开机次数 操作设置 pages/device/setDevStartup/index -->
                <template #operationStartup="{ row }">
                   <div>
                        <i class="el-icon-setting font_bule"></i>
                        <a class="font_bule cursor_pointer ml5" @click.stop="operaStartupHandle(row)"> 开机次数 </a>
                   </div>
                </template>
            </ElTable>
        </div>
        <ayjDialog ref="ayjDialogRef" :fullscreen="false" width="90%" top="3vh" :title="customerRow.name + '详情'" :slotFooter="false">
            <template v-if="customerRow.id">
               <div style="height: 86vh;">
                <customersThree ref="customersThreeRef" :xsgf="15" :isDrawerOpen="true" :customerId="customerRow.id">
                </customersThree>
               </div>
            </template>
            <template v-else>
                <empty></empty>
            </template>
        </ayjDialog>
    </div>

</template>

<script setup>
import { ref, onMounted, getCurrentInstance, watch, onUnmounted, computed, onBeforeUnmount, defineProps, defineEmits, nextTick } from '@vue/composition-api'
import ElTable from '@/components/commV2/Table/index.vue'
import customCtrl from "@/js/custom/CustomCtrl.js";
import { useDynamicHeight } from '@/hooks/useDynamicHeight'
import customersThree from '@/components/customers/CustomersThree.vue';
import searchBar from './searchBar.vue'
import config from "@/js/conf/Config.js";

const { proxy } = getCurrentInstance()

// 使用动态高度 hooks
const containerRef = ref(null)
const pointsBoxRef = ref(null)
const { dynamicHeight, updateHeight } = useDynamicHeight({
    containerRef: containerRef,
    subtractRef: pointsBoxRef,
    extraHeight: 20
})

const pageSizeNum = 20

const props = defineProps({

    // 表格是否开启多选
    selection: {
        type: Boolean,
        default: false
    },

    // 表格是否单选，默认多选
    single: {
        type: Boolean,
        default: false
    },

    // 扩展操作 内容
    extraColumns: {
        type: Array,
        default: () => []
    },

    // 是否是引用  客户页面组件 ，有一些是客户页面组件自身需要定制的操作，外界组件不参与客户页面组件默认操作，不能写死
    isCite: {
        type: Boolean,
        default: false
    },

    // 引用组件是否显示标签，标签需要额外处理
    isShowTag: {
        type: Boolean,
        default: false
    },
    
})


// 客户列表相关状态
const isLoading = ref(false)
const tableData = ref([])
const tableRef = ref(null) // 添加表格引用
const customQuery = ref({
    typeid: "all", //客户类型
    orderby: "", //排序 1 创建时间 2 欠款额度 3 交易单数 4最近交易
    uid_cp: "", //	经手人
    group: "", //	非必须 筛选 1 30天内没消费客户 2 30天内新增客户
    idyun: "", //	云店id 非筛选项 不传该参数
    isyun: "", //	是否为云店客户 1是其他 否 非筛选项 不传该参数
    is_yy: "", //是否为预约 1是 其他否 默认否
    pfrom: 0, //	开始id 非必须 默认为0
    pnum: pageSizeNum, //每页数量 非必须 默认0
    province: "", //	省份搜索 int 省份code 非筛选项 不传该参数
    city: "", //城市搜索 int 市code 非筛选项 不传该参数
    area: "", //区域搜索 int 区域code 非筛选项 不传该参数
    customerid: "", //搜索客户id
    tagid: "", //标签id 非筛选项 不传该参数  18
})
const custPage = ref(0)
const pageSize = ref(pageSizeNum)
const hasMore = ref(false)

const isShowCp = ref(false)
const isShowName = ref(false)
const mySelf = ref(null)
const limitViewOtherCustom = ref(false)
const md = ref(null)

// 搜素数据集合
const searchData = ref({
    order_ls: [],
    custype_ls: [],
    group_ls: [],
    yd_ls: [],
    ucp_ls: []
})

onMounted(() => {
    // 获取客户列表
    getCustList()
    // 获取经手人列表
    createdUcpList()
    // 动态修改筛选器按钮样式
    applyFilterButtonStyles()
})


const ayjDialogRef = ref(null)
const customerRow = ref({})
const onView = (row) => {
    customerRow.value = row
    ayjDialogRef.value.open()
}

const onSearch = (query) => {
    onSelectRefresh(query)
}

const onRefresh = (query) => {
    onSelectRefresh(query)
}

const onSelectRefresh = (query) => {
    custPage.value = 0
    tableData.value = []
    customQuery.value = {
        ...customQuery.value,
        ...query
    }
    getCustList()
}

// 获取客户列表
const getCustList = async () => {
    if (isLoading.value) return
    // 设置查询条件
    if (!limitViewOtherCustom.value && mySelf.value) {
        customQuery.value.uid_cp = mySelf.value.uid
    }
    customQuery.value.is_yy = md.value == 15 ? 1 : ""
    customQuery.value.pfrom = custPage.value * pageSize.value
    try {
        isLoading.value = true
        await customCtrl.getCustList(customQuery.value, back)
        function back(response) {
            if (!response.data) return
            let data = response.data

            // 设置显示权限
            customCtrl.setIsShowCp(data.is_cp)
            customCtrl.setIsShowName(data.is_name)

            if (md.value != 15) {
                isShowCp.value = customCtrl.getIsShowCp()
                isShowName.value = customCtrl.getIsShowName()
            }

            // 处理客户列表数据
            if (data.custom_ls && data.custom_ls.length > 0) {
                tableData.value = tableData.value.concat(data.custom_ls)
                hasMore.value = data.custom_ls.length >= pageSizeNum
            } else {
                hasMore.value = false
            }
            // 避免不能分页,多调用一页数据  一页20条  数据小于40条时，多调用一页数据
            if (data?.custom_ls?.length > 0 && tableData.value.length >= pageSizeNum && tableData.value.length < pageSizeNum * 2) {
                custPage.value++
                getCustList()
            }

            // 排序列表
            if (data.order_ls && data.order_ls.length > 0) {
                searchData.value.order_ls = data.order_ls.map(item => ({
                    value: item.id,
                    label: item.name
                }))
            }
            // 客户类型列表
            if (data.custype_ls) {
                data.custype_ls.unshift({ id: "", title: "全部类型" })
                data.custype_ls.push({ id: "0", title: "未分类" })
                searchData.value.custype_ls = data.custype_ls.map(item => ({
                    value: item.id,
                    label: item.title
                }))
            }
            // 分组列表
            if (data.group_ls && data.group_ls.length > 0) {
                searchData.value.group_ls = data.group_ls.map(item => ({
                    value: item.id,
                    label: item.name
                }))
            }
            // 云端列表
            if (data.yd_ls && data.yd_ls.length > 0) {
                searchData.value.yd_ls = data.yd_ls.map(item => ({
                    value: item.idyun,
                    label: item.name
                }))
            }
            // 标签列表
            if (data.tag_ls && data.tag_ls.length > 0 && tableData.value.length > 0 && tableData.value.length <= pageSizeNum) {
                initializeFilters(data.tag_ls)
            }
        }
    } catch (error) {
        console.error('获取客户列表失败:', error)
    } finally {
        isLoading.value = false
    }
}

// 经办人数据
const createdUcpList = async () => {
    let param = {
        md: "xs",
        ch: 2
    }
    let res = await proxy.$api({ url: config.UCP_LS, data: param });
    if (res && res.status == 1) {
        if (!res.data) return;
        searchData.value.ucp_ls = res.data.map(item => ({
            value: item.uid,
            label: item.name
        }))
    }
}

const tagFilterOptions = ref([])

const columns = computed(() => {
    const baseColumns = [
        {
            label: '序号',
            type: 'index',
            width: 60,
            align: 'center',
            indexMethod: (index) => index + 1
        },
        { label: '用户名称', prop: 'name', slot: 'name', width: 250 },
        { label: '电话号码', prop: 'cellphone', width: 150 },
        { label: '所属公司', prop: 'company', slot: 'company' },
        { label: '交易金额', prop: 'amount_order', slot: 'amount_order', width: 150 },
        { label: '交易单数', prop: 'num_order', width: 100 },
        {
            label: '标签',
            prop: 'tag',
            slot: 'tag',
            filters: tagFilterOptions.value,
            filterMethod: filterByTag,
            filterMultiple: true,
            filterable: true,
        },
        { label: '创建时间', prop: 'atime', width: 150 }
    ]
    return props.isCite ? customColumns.value : baseColumns
})

const customColumns = computed(() => {
    if (!props.isShowTag) {
        return [...(props.extraColumns || [])]
    }
    
    const extraCols = [...(props.extraColumns || [])]
    const tagColumn = {
        label: '标签',
        prop: 'tag',
        slot: 'tag',
        filters: tagFilterOptions.value,
        filterMethod: filterByTag,
        filterMultiple: true,
        filterable: true,
    }
    
    // 如果extraCols为空，直接返回标签列
    if (extraCols.length === 0) {
        return [tagColumn]
    }
    
    // 将标签列插入到倒数第二列
    const insertIndex = Math.max(0, extraCols.length - 1)
    extraCols.splice(insertIndex, 0, tagColumn)
    return extraCols
})


const loadScroll = () => {
    if (isLoading.value || !hasMore.value) return
    custPage.value++
    getCustList()
}


// 定义 Emits
const emit = defineEmits([
    'operaStartupHandleEmit',
])

// 操作事件---------------------  start  ---------------------

// 开机次数 操作设置 pages/device/setDevStartup/index
const operaStartupHandle = (e) => {
    emit('operaStartupHandleEmit', e)
}

// 操作事件---------------------  end  ---------------------


// 选择项目变化，触发事件
const onSelectionChange = (val) => {
    // 多选数据
    console.log('选中的数据==', val)
}

// 点击当前高亮项目，触发事件
const onCurrentChange = (val) => {
    console.log('点击当前高亮项目，触发事件=', val)
}

// 排序函数
const onSortChange = (val) => {
    return
}

// 获取标签类型/颜色
const getTagType = (index) => {
    const tagTypes = ['', 'success', 'info', 'warning', 'danger']
    return tagTypes[index % tagTypes.length]
}

const filterByTag = (value, row, column) => {
    // 这里不做实际筛选，因为我们要通过后台接口获取筛选数据
    // 返回 true 让所有数据都显示，实际筛选由后台处理
    return true
}

// 初始化筛选器选项
const initializeFilters = (tagList) => {
    console.log('初始化标签筛选器:', tagList)
    if (!tagList || !Array.isArray(tagList)) {
        console.log('标签数据无效')
        return
    }
    // 将后台返回的标签数据转换为筛选器格式
    tagFilterOptions.value = tagList.map(tag => {
        // 处理不同的数据格式
        let text, value

        if (typeof tag === 'string') {
            // 如果是字符串
            text = tag
            value = tag
        } else if (typeof tag === 'object') {
            // 如果是对象，尝试不同的属性名
            text = tag.title || tag.name || tag.label || tag.text || String(tag.id)
            value = tag.id || tag.value || tag.title || tag.name || tag.label
        } else {
            // 其他类型转为字符串
            text = String(tag)
            value = String(tag)
        }
        return { text, value }
    })
    // 更新标签列的筛选器
    const tagColumn = columns.value.find(col => col.prop === 'tag')
    if (tagColumn) {
        tagColumn.filters = tagFilterOptions.value
        // 强制更新表格布局
        nextTick(() => {
            if (tableRef.value && tableRef.value.doLayout) {
                tableRef.value.doLayout()
            }

            // 额外的强制更新
            setTimeout(() => {
                if (tableRef.value && tableRef.value.elTableRef) {
                    tableRef.value.elTableRef.doLayout()
                }
            }, 100)
        })
    }
}

// 动态修改筛选器按钮样式
const applyFilterButtonStyles = () => {
    // 等待DOM更新
    nextTick(() => {
        const observer = new MutationObserver(() => {
            const filterBottoms = document.querySelectorAll('.el-table-filter__bottom')
            filterBottoms.forEach(bottom => {
                const buttons = bottom.querySelectorAll('button')
                if (buttons.length >= 2) {
                    // 第一个按钮（筛选）
                    const filterBtn = buttons[0]
                    filterBtn.style.cssText = `
                        margin-right: 8px !important;
                        border: 1px solid #dcdfe6 !important;
                        border-radius: 4px !important;
                    `
                    // 第二个按钮（重置）
                    const resetBtn = buttons[1]
                    resetBtn.style.cssText = `
                        background: #f5f5f5 !important;
                        color: #606266 !important;
                        border: 1px solid #dcdfe6 !important;
                        border-radius: 4px !important;
                    `
                }
            })
        })
        observer.observe(document.body, {
            childList: true,
            subtree: true
        })
        // 5秒后停止观察
        setTimeout(() => observer.disconnect(), 5000)
    })
}

// 新增的筛选器变化事件
const onFilterChange = (filters) => {
    console.log('筛选器状态:', filters)
    // Element UI 返回的筛选器数据格式是 { "el-table_3_column_23": ["54", "46"] }
    // 我们需要找到标签列对应的筛选数据
    let tagFilterValues = []
    const tagColumnIndex = columns.value.findIndex(col => col.prop === 'tag')
    console.log('标签列索引:', tagColumnIndex)
    if (tagColumnIndex !== -1) {
        // 查找包含列索引的键名
        const filterKey = Object.keys(filters).find(key => {
            // Element UI 的键名格式通常是 el-table_X_column_Y
            // 其中 Y 是列的索引（从某个数字开始计算）
            const match = key.match(/column_(\d+)/)
            if (match) {
                const columnNum = parseInt(match[1])
                // 可能需要调整这个计算，因为Element UI的列索引可能包含选择列等
                return columnNum === tagColumnIndex ||
                    columnNum === tagColumnIndex + 1 ||
                    columnNum === tagColumnIndex + 2  // 考虑序号列的影响
            }
            return false
        })
        console.log('找到的筛选器键名:', filterKey)
        if (filterKey && filters[filterKey]) {
            tagFilterValues = filters[filterKey]
        }
    }

    // 方法2: 如果方法1失败，使用备用方案（获取第一个筛选器）
    if (tagFilterValues.length === 0) {
        const filterKeys = Object.keys(filters)
        if (filterKeys.length > 0) {
            const firstKey = filterKeys[0]
            const filterValue = filters[firstKey]
            if (Array.isArray(filterValue)) {
                tagFilterValues = filterValue
            }
        }
    }
    // 处理标签筛选
    if (tagFilterValues.length > 0) {
        // 将筛选的标签值传递给查询参数
        customQuery.value.tagid = tagFilterValues.join(',')
    } else {
        customQuery.value.tagid = ''
    }
    custPage.value = 0
    tableData.value = []
    getCustList()
}

</script>

<style lang="scss" scoped>
.container-page {
    box-sizing: border-box;
    width: 100%;
    height: 100%;
    padding: 10px;
    background: linear-gradient(90deg, #f6f4f7 0%, #faf3fb 100%);
}

.container-card {
    box-sizing: border-box;
    padding: 8px;
    border-radius: 10px;
    height: 100%;
    width: 100%;
    border: 1px solid #fff;
    position: relative;
    overflow: hidden;
}

.El-table {
    position: absolute;
    height: 100%;
    width: 99%;
}

.pd0 {
    padding: 0 !important;
}


.avatar {
    height: 34px;
    width: 34px;
    border-radius: 50%;
}

.tag-container {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
    align-items: center;
}

.tag-item {
    margin: 0;
    max-width: 140px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

.no-tags {
    color: #999;
    font-size: 12px;
}

.bold {
    font-weight: bold;
}
</style>
